<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库">
              <j-dict-select-tag
                default-select-first
                placeholder="请选择仓库"
                v-model="queryParam.warehouseCode"
                dictCode="wms_warehouse,warehouse_name,warehouse_code"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物料名称">
              <a-input placeholder="请输入物料名称" v-model="queryParam.materialName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物料编码">
              <a-input placeholder="请输入物料编码" v-model="queryParam.materialCode"></a-input>
            </a-form-item>
          </a-col>
          <!-- <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item label="制单日期">
              <j-date
                :show-time="true"
                date-format="YYYY-MM-DD"
                placeholder="请选择开始时间"
                class="query-group-cust"
                v-model="queryParam.createTimeBegin"
              ></j-date>
              <span class="query-group-split-cust"></span>
              <j-date
                :show-time="true"
                date-format="YYYY-MM-DD"
                placeholder="请选择结束时间"
                class="query-group-cust"
                v-model="queryParam.createTimeEnd"
              ></j-date>
            </a-form-item>
          </a-col> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAddTo" type="primary" icon="plus">添加</a-button>
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('入库单')">导出</a-button>
      <a-button type="primary" icon="printer" @click="handlePrint">标签打印</a-button>
      <a-button type="primary" icon="printer" @click="handleLabelPrint">标签补打</a-button>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="inbound_order_item_id"
        class="j-table-force-nowrap1"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template slot="remark" slot-scope="text, record">
          <div v-if="record.creatorRemark">制单人:{{ record.creatorRemark }}</div>
          <div v-if="record.inspectorRemark">检验人:{{ record.inspectorRemark }}</div>
        </template>
        <span slot="action" slot-scope="text, record">
          <a v-if="procurementType.includes(record.entryType)" @click="handleStoreDetail(record)">附件查看</a>
        </span>
      </a-table>
    </div>

    <inbound-record-new-modal ref="newModalForm" @ok="modalFormOk" />
    <inbound-record-modal ref="modalForm" @ok="modalFormOk" />
    <inbound-record-label-generate-print-modal ref="printModalForm" @ok="modalFormOk" />
    <inbound-record-label-list-print-modal ref="labelPrintModalForm" @ok="modalFormOk" />
    <inbound-store-modal ref="storeModalForm" @ok="modalFormOk" />
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import InboundRecordNewModal from './modules/InboundRecordNewModal.vue'
import InboundRecordModal from './modules/InboundRecordModal.vue'
import '@/assets/less/TableExpand.less'
import dayjs from 'dayjs'
import InboundRecordLabelGeneratePrintModal from './modules/InboundRecordLabelGeneratePrintModal.vue'
import InboundRecordLabelListPrintModal from './modules/InboundRecordLabelListPrintModal.vue'
import { getAction, postAction } from '@api/manage'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import InboundStoreModal from './modules/InboundStoreModal.vue'

export default {
  name: 'InboundOrderList',
  mixins: [JeecgListMixin],
  components: {
    InboundRecordLabelListPrintModal,
    InboundRecordLabelGeneratePrintModal,
    InboundRecordModal,
    InboundRecordNewModal,
    InboundStoreModal,
  },
  data() {
    return {
      description: '入库单管理页面',
      disableMixinCreated: true,
      activeKey: 'notGenerated',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          fixed: 'left',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '入库类型',
          align: 'center',
          dataIndex: 'entryType_dictText',
          sorter: (a, b) => {
            const valA = a.entryType_dictText || ''
            const valB = b.entryType_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
          fixed: 'left',
        },
        {
          title: '单据号',
          align: 'center',
          dataIndex: 'documentNumber',
          sorter: (a, b) => {
            const valA = a.documentNumber || ''
            const valB = b.documentNumber || ''
            return valA.localeCompare(valB, 'en')
          },
          fixed: 'left',
        },
        /*
        {
          title: '入库单号',
          align: 'center',
          dataIndex: 'entryNumber',
          fixed: 'left'
        },
         */
        {
          title: '已入库数量',
          align: 'center',
          dataIndex: 'storedQuantity',
          sorter: (a, b) => {
            const valA = a.storedQuantity;
            const valB = b.storedQuantity;
            if (valA == null && valB == null) return 0;
            if (valA == null) return 1;
            if (valB == null) return -1;
            return Number(valA) - Number(valB);
          }
        },
        {
          title: '未入库数量',
          align: 'center',
          dataIndex: 'unstoredQuantity',
          sorter: (a, b) => {
            const valA = a.unstoredQuantity;
            const valB = b.unstoredQuantity;
            if (valA == null && valB == null) return 0;
            if (valA == null) return 1;
            if (valB == null) return -1;
            return Number(valA) - Number(valB);
          }
        },
        {
          title: '客户物料编码',
          align: 'center',
          dataIndex: 'customerMaterialCode',
          sorter: (a, b) => {
            const valA = a.customerMaterialCode || ''
            const valB = b.customerMaterialCode || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '物料编码',
          align: 'center',
          dataIndex: 'materialCode',
          sorter: (a, b) => {
            const valA = a.materialCode || ''
            const valB = b.materialCode || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName',
          sorter: (a, b) => {
            const valA = a.materialName || ''
            const valB = b.materialName || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'specificationModel',
          sorter: (a, b) => {
            const valA = a.specificationModel || ''
            const valB = b.specificationModel || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        // {
        //   title: '物料描述',
        //   align: 'center',
        //   dataIndex: 'materialDesc'
        // },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText',
          sorter: (a, b) => {
            const valA = a.unit_dictText || ''
            const valB = b.unit_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '数量',
          align: 'center',
          dataIndex: 'quantity',
          sorter: (a, b) => {
            const valA = a.quantity;
            const valB = b.quantity;
            if (valA == null && valB == null) return 0;
            if (valA == null) return 1;
            if (valB == null) return -1;
            return Number(valA) - Number(valB);
          }
        },
        {
          title: '辅单位',
          align: 'center',
          dataIndex: 'secondaryUnit_dictText',
          sorter: (a, b) => {
            const valA = a.secondaryUnit_dictText || ''
            const valB = b.secondaryUnit_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '辅数量',
          align: 'center',
          dataIndex: 'secondaryQuantity',
          sorter: (a, b) => {
            const valA = a.secondaryQuantity;
            const valB = b.secondaryQuantity;
            if (valA == null && valB == null) return 0;
            if (valA == null) return 1;
            if (valB == null) return -1;
            return Number(valA) - Number(valB);
          }
        },
        {
          title: '宝洁订单号',
          align: 'center',
          dataIndex: 'pgOrderNumber',
          sorter: (a, b) => {
            const valA = a.pgOrderNumber || ''
            const valB = b.pgOrderNumber || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '订单编号',
          align: 'center',
          dataIndex: 'orderNumber',
          sorter: (a, b) => {
            const valA = a.orderNumber || ''
            const valB = b.orderNumber || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '生产车间',
          align: 'center',
          dataIndex: 'productionShop_dictText',
          sorter: (a, b) => {
            const valA = a.productionShop_dictText || ''
            const valB = b.productionShop_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '生产日期',
          align: 'center',
          dataIndex: 'productionDate',
          customRender: function (text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
          sorter: (a, b) => {
            const valA = a.productionDate || ''
            const valB = b.productionDate || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '保质期（天）',
          align: 'center',
          dataIndex: 'shelfLife',
          sorter: (a, b) => {
            const valA = a.shelfLife;
            const valB = b.shelfLife;
            if (valA == null && valB == null) return 0;
            if (valA == null) return 1;
            if (valB == null) return -1;
            return Number(valA) - Number(valB);
          }
        },
        {
          title: '限用日期',
          align: 'center',
          dataIndex: 'expirationDate',
          customRender: function (text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
          sorter: (a, b) => {
            const valA = a.expirationDate || ''
            const valB = b.expirationDate || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '批次号',
          align: 'center',
          dataIndex: 'batchNumber',
          sorter: (a, b) => {
            const valA = a.batchNumber || ''
            const valB = b.batchNumber || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '物料批号',
          align: 'center',
          dataIndex: 'materialBatchNumber',
          sorter: (a, b) => {
            const valA = a.materialBatchNumber || ''
            const valB = b.materialBatchNumber || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '储位',
          align: 'center',
          dataIndex: 'storageLocation_dictText',
          sorter: (a, b) => {
            const valA = a.storageLocation_dictText || ''
            const valB = b.storageLocation_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '质检状态',
          align: 'center',
          dataIndex: 'qualityInspectionStatus_dictText',
          sorter: (a, b) => {
            const valA = a.qualityInspectionStatus_dictText || ''
            const valB = b.qualityInspectionStatus_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '供应商名称',
          align: 'center',
          dataIndex: 'supplierName',
          sorter: (a, b) => {
            const valA = a.supplierName || ''
            const valB = b.supplierName || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '宝洁采购订单号',
          align: 'center',
          dataIndex: 'pgPurchaseOrderNumber',
          sorter: (a, b) => {
            const valA = a.pgPurchaseOrderNumber || ''
            const valB = b.pgPurchaseOrderNumber || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '宝洁供应商编号',
          align: 'center',
          dataIndex: 'pgSupplierCode',
          sorter: (a, b) => {
            const valA = a.pgSupplierCode || ''
            const valB = b.pgSupplierCode || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '宝洁供应商',
          align: 'center',
          dataIndex: 'pgSupplierName',
          sorter: (a, b) => {
            const valA = a.pgSupplierName || ''
            const valB = b.pgSupplierName || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '客户名称',
          align: 'center',
          dataIndex: 'customerName',
          sorter: (a, b) => {
            const valA = a.customerName || ''
            const valB = b.customerName || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '物料分类1',
          align: 'center',
          dataIndex: 'materialClassify_dictText',
          sorter: (a, b) => {
            const valA = a.materialClassify_dictText || ''
            const valB = b.materialClassify_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '物料分类2',
          align: 'center',
          dataIndex: 'brand_dictText',
          sorter: (a, b) => {
            const valA = a.brand_dictText || ''
            const valB = b.brand_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '更新时间',
          align: 'center',
          dataIndex: 'updateTime',
          customRender: function (text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
          sorter: (a, b) => {
            const valA = a.updateTime || ''
            const valB = b.updateTime || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '制单人',
          align: 'center',
          dataIndex: 'createBy_dictText',
          sorter: (a, b) => {
            const valA = a.createBy_dictText || ''
            const valB = b.createBy_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '制单部门',
          align: 'center',
          dataIndex: 'sysOrgCode_dictText',
          sorter: (a, b) => {
            const valA = a.sysOrgCode_dictText || ''
            const valB = b.sysOrgCode_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '制单日期',
          align: 'center',
          dataIndex: 'createTime',
          customRender: function (text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
          sorter: (a, b) => {
            const valA = a.createTime || ''
            const valB = b.createTime || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        // {
        //   title:'制单人备注',
        //   align:"center",
        //   dataIndex: 'creatorRemark'
        // },
        {
          title: '检验标准',
          align: 'center',
          dataIndex: 'inspectionStandard',
          sorter: (a, b) => {
            const valA = a.inspectionStandard || ''
            const valB = b.inspectionStandard || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '抽检数量',
          align: 'center',
          dataIndex: 'samplingQuantity',
          sorter: (a, b) => {
            const valA = a.samplingQuantity;
            const valB = b.samplingQuantity;
            if (valA == null && valB == null) return 0;
            if (valA == null) return 1;
            if (valB == null) return -1;
            return Number(valA) - Number(valB);
          }
        },
        {
          title: '检验结果',
          align: 'center',
          dataIndex: 'inspectionResult',
          sorter: (a, b) => {
            const valA = a.inspectionResult || ''
            const valB = b.inspectionResult || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '检验人',
          align: 'center',
          dataIndex: 'inspector_dictText',
          sorter: (a, b) => {
            const valA = a.inspector_dictText || ''
            const valB = b.inspector_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '检验部门',
          align: 'center',
          dataIndex: 'inspectionDeptCode_dictText',
          sorter: (a, b) => {
            const valA = a.inspectionDeptCode_dictText || ''
            const valB = b.inspectionDeptCode_dictText || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        {
          title: '检验日期',
          align: 'center',
          dataIndex: 'inspectionDate',
          customRender: function (text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          },
          sorter: (a, b) => {
            const valA = a.inspectionDate || ''
            const valB = b.inspectionDate || ''
            return valA.localeCompare(valB, 'en')
          },
        },
        // 备注
        // 制单人备注：
        // 检验人备注：
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'remark' },
        },
        // {
        //   title:'检验人备注',
        //   align:"center",
        //   dataIndex: 'inspectorRemark'
        // },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 80,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/wms/inbound/inbound-order/list',
        delete: '/wms/inbound/inbound-order/delete',
        deleteBatch: '/wms/inbound/inbound-order/deleteBatch',
        exportXlsUrl: '/wms/inbound/inbound-order/exportXls',
        importExcelUrl: 'basic/inboundOrder/importExcel',
      },
      dictOptions: {},
      superFieldList: [],
      queryParam: {
        warehouseCode: null,
        // createTimeBegin: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
        // createTimeEnd: dayjs().format('YYYY-MM-DD'),
      },
      procurementType: [1, 2, 3, 4, 13, 14, 15, 16],
    }
  },
  watch: {
    'queryParam.warehouseCode': {
      handler(newVal) {
        if (newVal) {
          this.loadData()
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getSuperFieldList()
    if (this.queryParam.warehouseCode) {
      this.loadData()
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    initDictConfig() {},
    getSuperFieldList() {
      this.superFieldList = []
    },
    handleAdd() {
      if (!this.queryParam.warehouseCode) {
        this.$message.warning('请先选择仓库')
        return
      }
      this.$refs.newModalForm.add()
      this.$refs.newModalForm.title = '新增'
      this.$refs.newModalForm.warehouseCode = this.queryParam.warehouseCode
      this.$refs.newModalForm.disableSubmit = false
    },
    handleAddTo() {
      if (!this.selectionRows || this.selectionRows.length === 0) {
        this.$message.warning('请先选中一条记录')
        return
      }
      const { entryNumber } = this.selectionRows[0]
      if (this.selectionRows.some((row) => row.entryNumber !== entryNumber)) {
        this.$message.warning('请选择同一单据的记录')
        return
      }
      if (this.selectionRows.every((row) => row.entryType === 8)) {
        if (this.selectionRows.length > 1) {
          this.$message.error('最多只能选择一条调拨记录')
          return
        }
        this.$confirm({
          title: '确认入库?',
          onOk: () => {
            this.handleTransfer()
          },
        })
        return
      }
      // if (this.selectionRows.every((row) => row.entryType === 10)) {
      //   if (this.selectionRows.length > 1) {
      //     this.$message.error('最多只能选择一条包装作业入库记录')
      //     return
      //   }
      //   this.$confirm({
      //     title: '确认入库?',
      //     onOk: () => {
      //       this.handlePackageWork()
      //     },
      //   })
      //   return
      // }
      this.$refs.modalForm.add(this.selectionRows)
      this.$refs.modalForm.title = '添加'
      this.$refs.modalForm.warehouseCode = this.queryParam.warehouseCode
      this.$refs.modalForm.disableSubmit = false
    },
    handleTransfer() {
      if (!this.selectValidate()) {
        return
      }
      if (this.selectionRows[0].entryType !== 8) {
        this.$message.warning('只能选择入库类型为调拨入库的记录')
        return
      }
      const main = Object.assign({}, this.selectionRows[0])
      const params = { id: main.id }
      const that = this
      getAction('/wms/inbound/inbound-order/queryInboundOrderItemByMainId', params).then(({ result }) => {
        if (result && result.length > 0) {
          const inboundRecordItemList = result
          inboundRecordItemList.forEach((item) => {
            item.inboundOrderItemId = item.id
            item.id = null
          })
          main.inboundOrderId = main.id
          main.id = null
          main.creator = main.createBy
          main.creatorDeptCode = main.sysOrgCode
          main.creationDate = main.createTime
          main.entryDate = dayjs().format('YYYY-MM-DD')
          const formData = { ...main, inboundRecordItemList }
          postAction('/wms/inbound/inbound-record/add', formData).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    },
    handlePackageWork() {
      if (!this.selectValidate()) {
        return
      }
      if (this.selectionRows[0].entryType !== 10) {
        this.$message.warning('只能选择入库类型为包装作业入库的记录')
        return
      }
      const main = Object.assign({}, this.selectionRows[0])
      const params = { id: main.id }
      const that = this
      getAction('/wms/inbound/inbound-order/queryInboundOrderItemByMainId', params).then(({ result }) => {
        if (result && result.length > 0) {
          const inboundRecordItemList = result
          inboundRecordItemList.forEach((item) => {
            item.inboundOrderItemId = item.id
            item.id = null
          })
          main.inboundOrderId = main.id
          main.id = null
          main.creator = main.createBy
          main.creatorDeptCode = main.sysOrgCode
          main.creationDate = main.createTime
          main.entryDate = dayjs().format('YYYY-MM-DD')
          const formData = { ...main, inboundRecordItemList }
          postAction('/wms/inbound/inbound-record/add', formData).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
            } else {
              that.$message.warning(res.message)
            }
          })
        }
      })
    },
    selectValidate() {
      if (!this.selectionRows || this.selectionRows.length === 0) {
        this.$message.warning('请先选中一条记录')
        return false
      }
      if (this.selectionRows.length > 1) {
        this.$message.error('最多只能选择一条记录')
        return false
      }
      return true
    },
    searchReset() {
      const warehouseCode = this.queryParam.warehouseCode
      this.queryParam = {
        warehouseCode,
      }
      this.loadData(1)
    },
    handlePrint() {
      if (!this.selectValidate()) {
        return
      }
      this.$refs.printModalForm.print(this.selectionRows[0])
      this.$refs.printModalForm.title = '标签打印'
    },
    handleLabelPrint() {
      if (!this.selectValidate()) {
        return
      }
      this.$refs.labelPrintModalForm.list(this.selectionRows[0])
      this.$refs.labelPrintModalForm.title = '标签补打'
    },
    handleStoreDetail(record){
      this.$refs.storeModalForm.edit(record)
      this.$refs.storeModalForm.title = '附件查看'
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
